function Connection(host,port,handler){
	this.ip = host;
	this.port = port;
	this.socket = new WebSocket("ws://"+ host + ":" + port+"/delivery");
	this.socket.onmessage = function(event) { handler.process(event.data); };
	this.socket.onopen = function(event) { };
	this.socket.onclose = function(event) { };
}

Connection.prototype.send = function(message) {
	if(!message.checkBeforeSend()) {
		return;
	}
	var params = message.write();
	var stream = $.toJSON({type:message.type,data:params});
	this.socket.send(stream);
}

function GlobalHandler() {
	this.protocals = new Map(100);
	this.handlers = new Map(100);
	this.dummyHandler = new DummyHandler();
}
GlobalHandler.prototype.register = function(protocalType,ProtocalClazz,handler) {
	this.protocals.put(protocalType, ProtocalClazz);
	this.handlers.put(protocalType, handler);
}
GlobalHandler.prototype.getProtocal = function(protocalType) {
	return this.protocals.get(protocalType);
}
GlobalHandler.prototype.getHandler = function(protocalType) {
	var handler = this.handlers.get(protocalType);
	if(handler) {
		return handler;
	}
	return dummyHandler;
}
GlobalHandler.prototype.process = function(rawmsg) {
	var jraw = eval('('+rawmsg+')');
	var protocalClazz = this.protocals.get(jraw.type);
	var handler = this.handlers.get(jraw.type);
	if(protocalClazz) {
		var protocal = new protocalClazz;
		protocal.read(jraw.data);
		handler.process(protocal);
	}
}

function extendz(a,b) {
	a.prototype = new b();
	a.prototype.constructor = a;
}
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function isnull(a) {
	if(a == undefined || a == "") {
		return true;
	}
	return false;
}

function BaseHandler() {
	
}
BaseHandler.prototype.process = function() {}

function DummyHandler() {
	BaseHandler.call(this);
}
extendz(DummyHandler,BaseHandler);
DummyHandler.prototype.process = new function(){}

function BaseProtocal() {
	this.type;
}
BaseProtocal.prototype.read = function(data) {}
BaseProtocal.prototype.write = function(){return null;}
BaseProtocal.prototype.checkBeforeSend = function(){return true;}
